<template>
	<view class="login-and-register">
		<view class="login-btn-box" v-if="type == 1 || type == 3 || type == 4" @click="show()">
			<slot></slot>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<button v-else open-type="getPhoneNumber" @getphonenumber="getWxPhoneNumber" :style="buttonStyles" data-type="2">{{text}}</button>
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<button v-else open-type="getAuthorize" onError="onAuthError" @getAuthorize="getAliPhoneNumber" scope="phoneNumber" data-type="2"
			:style="buttonStyles">{{text}}</button>
		<!-- #endif -->
		<!-- 注册会员 -->
		<qh-popup v-model="showRegisterPopup" :title="popupTitle" @confirm="toRegister" :showButton="type == 3 || type == 4" confirmText="注册会员">
			<view class="login-popup-content">
				<template v-if="type == 1">
					<template v-if="isLogined">
						<view class="popup-auth-message-1">您确认重新获取头像与昵称？</view>
					</template>
					<template v-else>
						<view class="popup-auth-title">您还未登录</view>
						<view class="popup-auth-message">登录后将可享受更多服务</view>
						<view class="popup-auth-image-box">
							<image class="popup-auth-image" mode="aspectFit" v-if="loginImg" :src="loginImg"></image>
						</view>
					</template>
				</template>
				<template v-else>
					<view class="tips" v-if="type != 4">获取用户头像、昵称，主要用于向用户提供具有辨识度的用户中心界面</view>
					<view class="tips">获取用户手机号，主要用于会员在线上线下产生的数据互通，便于用户查看记录</view>
					<view class="flex-spe-cn">
						<view class="primary-color" @click="toBindVipBefore">已有会员？去绑定</view>
					</view>
				</template>
				<view class="form-box" :class="{'border-top': type == 3}">
					<template v-if="type != 4">
						<view class="form-list flex-cn border-bottom">
							<view class="form-list-title">头像</view>
							<view class="form-list-content flex-cn">
								<!-- #ifdef MP-WEIXIN -->
								<view class="flex-cn" @click="chooseImage">
									<qh-user-head-img :src="form.avatar" size="100" bgColor="#CCCCCC" color="#FFFFFF"></qh-user-head-img>
									<view class="pl mar_l_20" v-if="!form.avatar">点击上传头像</view>
								</view>
								<button v-if="canIUse" class="form-list-button" open-type="chooseAvatar" @chooseavatar="chooseAvatar"></button>
								<!-- #endif -->
								<!-- #ifdef MP-ALIPAY -->
								<qh-user-head-img :src="form.avatar" size="100" bgColor="#CCCCCC" color="#FFFFFF"></qh-user-head-img>
								<view class="pl mar_l_20" v-if="type == 3 && !form.avatar">点击授权登录</view>
								<button v-if="type == 3" class="form-list-button" @tap="bindGetAlipayUserInfo"></button>
								<!-- #endif -->
							</view>
						</view>
						<view class="form-list flex-cn border-bottom">
							<view class="form-list-title">昵称</view>
							<view class="form-list-content flex-spb-cn">
								<!-- #ifdef MP-WEIXIN -->
								<input v-model="form.nickname" type="nickname" class="form-list-input" placeholder="请输入昵称" placeholder-class="pl"
									maxlength="20">
								<!-- #endif -->
								<!-- #ifdef MP-ALIPAY -->
								<input v-model="form.nickname" type="nickname" readonly class="form-list-input" :placeholder="type == 3 ? '点击授权登录' : '登录后获取'"
									placeholder-class="pl">
								<button v-if="type == 3" class="form-list-button" @tap="bindGetAlipayUserInfo"></button>
								<!-- #endif -->
							</view>
						</view>
					</template>
					<view class="form-list flex-cn border-bottom" v-if="type == 3 || type == 4">
						<view class="form-list-title">手机号</view>
						<view class="form-list-content flex-spb-cn">
							<!-- #ifdef MP-WEIXIN -->
							<input v-model="form.phone" type="number" class="form-list-input" placeholder="点击授权" placeholder-class="pl">
							<button open-type="getPhoneNumber" class="form-list-button" @getphonenumber="getWxPhoneNumber">点击授权</button>
							<!-- #endif -->
							<!-- #ifdef MP-ALIPAY -->
							<input v-model="form.phone" type="number" class="form-list-input" placeholder-class="pl" placeholder="点击授权">
							<button open-type="getAuthorize" class="form-list-button" onError="onAuthError" @getAuthorize="getAliPhoneNumber"
								scope="phoneNumber">点击授权</button>
							<!-- #endif -->
						</view>
					</view>
				</view>

				<template v-if="type == 1">
					<!-- #ifdef MP-WEIXIN -->
					<qh-bottom-button customStyle="padding:36rpx 56rpx 50rpx" @cancel="showRegisterPopup = false" cancelStyle="border:none;background:#F2F3F5"
						:cancelText="isLogined ? '取消' : '暂不登录'" @confirm="submitUserData" :confirmText="isLogined ? '提交' : '立即登录'"></qh-bottom-button>
					<!-- #endif -->
					<!-- #ifdef MP-ALIPAY -->
					<qh-bottom-button customStyle="padding:36rpx 56rpx 50rpx" @cancel="showRegisterPopup = false" cancelStyle="border:none;background:#F2F3F5"
						:cancelText="isLogined ? '取消' : '暂不登录'">
						<button slot="confirm" class="popup-login-btn" @tap="bindGetAlipayUserInfo">{{isLogined ? '重新获取' : '立即登录'}}</button>
					</qh-bottom-button>
					<!-- #endif -->
				</template>
			</view>
		</qh-popup>
		<!-- 输入会员支付密码 -->
		<template-password v-if="showSetPassword" v-model="password" @success="bindVip" @cancel="cancelBindvip"></template-password>
		<!-- 绑定会员 -->
		<qh-center-popup v-model="showBindPopup" title="温馨提示" :showCancel="false" :showConfirm="false" showClose contentStyle="padding: 20rpx 0 0">
			<!-- #ifdef MP-WEIXIN -->
			<view class="tips text-center mar_l_30 mar_r_30">请确保您已设置头像、昵称</view>
			<!-- #endif -->
			<view class="mar_t_20 text-center mar_l_30 mar_r_30">此操作将获取您的手机号进行会员绑定</view>
			<view class="bind-vip-btn-box border-top flex-cn mar_t_60">
				<view class="bind-vip-btn cancel border-right" @click="showBindPopup = false">取消</view>
				<!-- #ifdef MP-WEIXIN -->
				<button open-type="getPhoneNumber" @getphonenumber="getWxPhoneNumber" data-type="2" class="bind-vip-btn confirm">点击绑定</button>
				<!-- #endif -->
				<!-- #ifdef MP-ALIPAY -->
				<button open-type="getAuthorize" onError="onAuthError" @getAuthorize="getAliPhoneNumber" scope="phoneNumber" data-type="2"
					class="bind-vip-btn confirm">点击绑定</button>
				<!-- #endif -->
			</view>
		</qh-center-popup>
		<!-- 自定义手机号 -->
		<qh-center-popup v-model="showInputPhone" title="设置手机号" showClose :confirmClose="false" @confirm="submitPhone" contentStyle="padding: 20rpx 0 0">
			<view class="login-popup-content">
				<view class="tips mar_l_20 mar_r_20">手机号获取失败，请您输入手机号</view>
				<view class="form-box">
					<view class="form-list flex-cn">
						<view class="form-list-title">手机号</view>
						<view class="form-list-content flex-spb-cn">
							<input v-model="custom.phone" :type="isBind ? 'text' : 'number'" class="form-list-input" placeholder-class="pl"
								:placeholder="'请输入手机号'+(isBind ? '/实体卡号' : '')" :maxlength="isBind ? 18 : 11">
						</view>
					</view>
					<view class="form-list flex-cn border-top" v-if="!isBind">
						<view class="form-list-title">验证码</view>
						<view class="form-list-content flex-spb-cn">
							<input v-model="custom.code" type="number" class="form-list-input" placeholder="请输入验证码" placeholder-class="pl">
						</view>
						<view class="get-code-btn">
							<text v-if="countDown == 0" @click="getCode">获取验证码</text>
							<text v-else>{{countDown}}s</text>
						</view>
					</view>
				</view>
			</view>
		</qh-center-popup>
	</view>
</template>

<script>
	import templatePassword from '@/components/template-password.vue';
	import {
		upload
	} from "@/request/index.js";
	export default {
		name: "login-and-register",
		components: {
			templatePassword,
		},
		props: {
			type: {
				type: [Number, String],
				default: 3,
			}, //类型  1仅登录  2换绑会员  3登录+注册会员  4注册会员
			text: {
				type: String,
				default: '',
			}, //按钮文字
			buttonStyle: {
				type: [Object, String],
				default () {
					return {}
				}
			},
			scene: {
				type: [Number, String],
				default: 0,
			}, //会员注册场景  0其他  1聚合码
		},
		emit: ['success', 'cancel-login', 'cancel-register'],
		data() {
			return {
				showRegisterPopup: false,
				isGetPhone: true, //是否是授权手机号
				changeAvatar: false, //是否更换头像
				isBind: false, //是否是绑定会员
				showSetPassword: false, //是否显示输入会员卡密码弹框
				showBindPopup: false, //是否显示绑定会员弹窗
				showInputPhone: false, //是否显示输入手机号弹窗
				password: '',
				countDown: 0,
				countDownTimer: null,
				loginImg: '',
				form: {
					avatar: '',
					nickname: '',
					phone: '',
					code: '',
				},
				custom: {
					phone: '',
					code: '',
				},
				prev_login_state: 0, //是否登录
				// #ifdef MP-WEIXIN
				canIUse: wx.canIUse('button.open-type.chooseAvatar'), //选择头像是否可用
				// #endif
			}
		},
		computed: {
			popupTitle() {
				let str = '';
				let type = this.type * 1;
				switch (type) {
					case 2:
						str = '获取手机号'
						break;
					case 4:
						str = '注册会员'
						break;
					case 3:
						str = '获取头像、昵称、手机号'
						break;
				}
				// console.log('popupTitle', str)
				return str;
			},
			buttonStyles() {
				return this.$joinStyle(this.buttonStyle);
			},
			isLogined() {
				return this.$store.userInfo.login_state == 1;
			},
		},
		async created() {
			await this.$onLaunched;
			if (this.$store.userInfo.login_state == 1) {
				this.form.avatar = this.$store.userInfo.avatar;
				this.form.nickname = this.$store.userInfo.nickname;
			}
			this.loginImg = this.$store.image_header + 'home-logo.png';
		},
		destroyed() {
			if (this.countDownTimer) {
				clearInterval(this.countDownTimer);
			}
		},
		methods: {
			show() {
				this.showRegisterPopup = true;
				this.prev_login_state = this.$store.userInfo.login_state;
			},
			// #ifdef MP-ALIPAY
			//登录获取用户信息
			bindGetAlipayUserInfo() {
				let token = uni.getStorageSync('valid_access_token');
				let token_time = token ? token.time : 0;
				let access_token = token ? token.value : '';
				if (!token_time || (new Date().getTime() - token_time) > 2 * 60 * 60 * 1000) {
					getApp().globalData.userLogin(() => {
						access_token = uni.getStorageSync('valid_access_token').value
						this.login(null, access_token);
					}, 'auth_user')
				} else {
					this.login(null, access_token);
				}
			},
			//获取手机号
			getAliPhoneNumber(e) {
				console.log('getAliPhoneNumber', e)
				this.isBind = false;
				my.getPhoneNumber({
					protocols: {
						isvAppId: getApp().globalData.XcxData.isvAppId, // 小程序模板所属的第三方应用APPID
					},
					success: (res) => {
						// console.log(res);
						let data = JSON.parse(res.response);
						console.log(data)
						if (data.response.code == '40001') {
							this.showInputPhone = true;
							return uni.showToast({
								title: data.response.subMsg,
								icon: 'none',
							})
						}
						this.getUserPhone({
							encryptedData: data.response,
							appId: getApp().globalData.XcxData.appid,
							verify_vip: this.$store.userInfo.type == 1 ? 0 : 1,
						}, e);
					},
					fail: (res) => {
						console.log('getAliPhoneNumber:fail', res);
						if (e.currentTarget.dataset.type == 2) {
							this.isBind = true;
						}
						this.showInputPhone = true;
						uni.showToast({
							title: '手机号获取失败，请手动填写',
							icon: 'none',
						});
					},
				});
			},
			// #endif
			// #ifdef MP-WEIXIN
			//选择头像
			chooseAvatar(e) {
				console.log('chooseAvatar', e)
				this.changeAvatar = true;
				this.form.avatar = e.detail.avatarUrl;
			},
			//版本过低，手动上传
			chooseImage() {
				if (this.canIUse) return;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['camera', 'album'],
					// 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						console.log(res);
						this.changeAvatar = true;
						this.form.avatar = res.tempFilePaths[0];
					}
				});
			},
			//获取手机号
			async getWxPhoneNumber(e) {
				console.log('getWxPhoneNumber', e)
				this.showBindPopup = false;
				this.isBind = false;
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					this.getUserPhone({
						new_phone: 1,
						iv: e.detail.iv,
						code: e.detail.code,
						appId: getApp().globalData.XcxData.appid,
						verify_vip: this.$store.userInfo.type == 1 ? 0 : 1,
					}, e);
				} else {
					if (e.currentTarget.dataset.type == 2) {
						this.isBind = true;
					}
					this.showInputPhone = true;
					uni.showToast({
						title: '您已拒绝授权手机号',
						icon: 'none',
						duration: 1000,
						mask: false
					});
				}
			},
			// #endif
			//获取手机号
			async getUserPhone(data, e, callback) {
				const res = await this.$request('SmallProgramApi/Vip/getPhone', data);
				if (res.status == 1) {
					if (this.type == 2) {
						//换绑会员
						this.showSetPassword = true;
						this.showRegisterPopup = false;
						this.custom.phone = res.data.phoneNumber;
						// console.log('换绑会员')
					} else if (e.currentTarget.dataset.type == 2) {
						this.form.phone = res.data.phoneNumber;
						// #ifdef MP-WEIXIN
						this.custom.phone = res.data.phoneNumber;
						if (getApp().globalData.XcxData.userInfo.login_state == 1) {
							// console.log('已注册')
							this.showSetPassword = true;
							this.showRegisterPopup = false;
						} else {
							// console.log('未注册')
							this.isBind = true;
							this.submitUserData();
						}
						// #endif
						// #ifdef MP-ALIPAY
						//绑定会员
						this.showSetPassword = true;
						this.showRegisterPopup = false;
						this.isBind = true;
						this.custom.phone = res.data.phoneNumber;
						// #endif
					} else {
						this.form.phone = res.data.phoneNumber;
						// #ifdef MP-ALIPAY
						//注册会员
						this.registerVip();
						// #endif
					}
				} else {
					if (e.currentTarget.dataset.type == 2) {
						this.isBind = true;
					}
					this.showInputPhone = true;
					uni.showToast({
						title: res.message ? res.message : '手机号获取失败，请重试',
						icon: 'none',
					});
				}
			},
			//获取验证码
			async getCode() {
				if (this.custom.phone.trim().length <= 0) return uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				if (!/^1[3456789]\d{9}$/.test(this.custom.phone)) return uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				});

				const res = await this.$request('SmallProgramApi/Vip/getCode', {
					phone: this.custom.phone
				});
				if (res.status == 1) {
					uni.showToast({
						title: res.message,
						icon: 'success',
					});
					this.countDown = 60;
					this.countDownTimer = setInterval(() => {
						this.countDown--;
						if (this.countDown == 0) {
							clearInterval(this.countDownTimer);
						}
					}, 1000)
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none',
					});
				}
			},
			//提交自定义手机号弹框
			submitPhone() {
				//手动填写的手机号
				if (this.custom.phone.trim().length <= 0) return uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				if (!/^1[3456789]\d{9}$/.test(this.custom.phone) && !this.isBind) return uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				});
				if (!this.isBind && (!this.custom.code || this.custom.code.length < 6)) return uni.showToast({
					title: '请输入6位数字验证码',
					icon: 'none'
				});
				this.isGetPhone = false;
				this.showInputPhone = false;
				this.showBindPopup = false;
				if (this.isBind) {
					//绑定会员
					this.showSetPassword = true;
					this.showRegisterPopup = false;
				} else {
					this.form.phone = this.custom.phone;
					this.form.code = this.custom.code;
				}
			},
			//显示绑定会员弹框
			toBindVipBefore() {
				if (!this.form.avatar) return uni.showToast({
					title: '请设置头像',
					icon: 'none',
				})
				if (!this.form.nickname) return uni.showToast({
					title: '请设置昵称',
					icon: 'none',
				})
				this.showBindPopup = true;
			},
			//提交注册
			toRegister() {
				this.isBind = false;
				this.submitUserData();
			},
			//提交
			async submitUserData() {
				if (this.type == 1 || this.type == 3) {
					//登录  登录+注册
					if (!this.form.avatar) return uni.showToast({
						// #ifdef MP-WEIXIN
						title: '请设置头像',
						// #endif
						// #ifdef MP-ALIPAY
						title: '请点击登录',
						// #endif
						icon: 'none',
					})
					if (!this.form.nickname) return uni.showToast({
						// #ifdef MP-WEIXIN
						title: '请设置昵称',
						// #endif
						// #ifdef MP-ALIPAY
						title: '请点击登录',
						// #endif
						icon: 'none',
					})
				}

				//注册会员 判断手机号
				if ((this.type == 3 || this.type == 4) && !this.form.phone) return uni.showToast({
					// #ifdef MP-WEIXIN
					title: '请授权手机号',
					// #endif
					// #ifdef MP-ALIPAY
					title: '请设置手机号',
					// #endif
					icon: 'none',
				})

				// #ifdef MP-ALIPAY
				this.registerVip();
				// #endif

				// #ifdef MP-WEIXIN
				if ((this.type == 1 || this.type == 3) && this.changeAvatar) {
					//上传头像
					const res = await upload({
						url: '/SmallProgramApi/Image/uploadAvatar',
						path: this.form.avatar,
						//这里是选取的图片的地址数组
						name: 'avatar',
					}, true)
					this.changeAvatar = false;
					this.login({
						nickname: this.form.nickname,
						avatar: res.data.path,
					})
				} else if (this.type == 4) {
					this.registerVip();
				} else {
					this.login({
						nickname: this.form.nickname,
						avatar: this.form.avatar,
					})
				}
				// #endif
			},
			//登录
			async login(userInfo, access_token = '') {
				const res = await this.$request('SmallProgramApi/Register/register', {
					nickname: userInfo && userInfo.nickname,
					avatar: userInfo && userInfo.avatar,
					share_uid: getApp().globalData.XcxData.share_uid ? getApp().globalData.XcxData.share_uid : '',
					access_token: access_token
				})
				if (res.status == 1) {
					if (this.type == 1) {
						//仅登录
						getApp().globalData.userLogin(() => {
							this.$emit('success', 'login');
							uni.showToast({
								title: this.prev_login_state != 1 ? '登录成功' : '更新成功'
							});
							this.showRegisterPopup = false;
						})
					} else {
						if (this.isBind) {
							//绑定会员
							this.showSetPassword = true;
							this.showRegisterPopup = false;
						} else {
							// #ifdef MP-WEIXIN
							//注册会员
							this.registerVip();
							// #endif
							// #ifdef MP-ALIPAY
							this.form.avatar = res.data.avatar;
							this.form.nickname = res.data.nickname;
							uni.showToast({
								title: '信息刷新成功'
							})
							getApp().globalData.userLogin(); //刷新用户信息
							// #endif
						}
					}
				} else {
					this.$emit('fail', res.message ? res.message : JSON.stringify(res));
				}
			},
			//注册会员
			async registerVip() {
				const res = await this.$request('SmallProgramApi/Vip/registerVip', {
					phone: this.form.phone,
					code: this.form.code,
					password: this.form.phone.substr(5, 10),
					share_uid: getApp().globalData.XcxData.share_uid ? getApp().globalData.XcxData.share_uid : '',
					scene: this.scene,
				});
				if (res.status == 1) {
					uni.showToast({
						title: res.message
					});
					getApp().globalData.userLogin(() => {
						this.$emit('success', 'register')
						uni.showToast({
							title: '注册成功'
						});
						this.showRegisterPopup = false;
					})
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none',
					});
					this.$emit('fail', res)
				}
			},
			//取消绑定会员
			cancelBindvip() {
				this.showSetPassword = false;
				if (this.type != 2) {
					this.showRegisterPopup = true;
				}
			},
			//绑定会员
			async bindVip() {
				const res = await this.$request('SmallProgramApi/Vip/bindCard_v1', {
					mobile_phone: this.custom.phone,
					password: this.password
				});
				if (res.status == 1) {
					this.showSetPassword = false;
					uni.showToast({
						title: res.message,
					});
					getApp().globalData.userLogin(() => {
						this.$emit('success', 'bind')
						uni.showToast({
							title: '绑定成功'
						});
					})
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
					this.$emit('fail', res);
				}
			},
		},
	}
</script>

<style lang="scss">
	.login-and-register {
		button {
			width: auto;
			padding: 0;
			margin: 0;
			background-color: transparent;
			font-size: 32rpx;
			line-height: 36rpx;
			/* #ifdef MP-ALIPAY */
			height: auto;
			border: none;
			/* #endif */

			&::after {
				border: none;
				border-radius: 0;
			}
		}

		.tips {
			font-size: 26rpx;
			line-height: 36rpx;
			color: #929397;
			padding: 10rpx;
			text-align: left;
		}

		.login-popup-content {
			padding: 20rpx 24rpx;
			box-sizing: border-box;
			width: 100%;
			overflow: hidden;


			.form-box {
				margin-top: 20rpx;

				.form-list {
					line-height: 36rpx;
					height: 140rpx;

					.form-list-title {
						width: 140rpx;
						font-size: 32rpx;
						color: #5F6267;
					}

					.form-list-content {
						flex: 1;
						height: 100%;
						overflow: hidden;
						position: relative;

						.form-list-input {
							width: 100%;
							height: 100%;
							font-size: 32rpx;
							color: #333333;
							text-align: left;
						}

						.form-list-button {
							width: 100%;
							height: 100%;
							position: absolute;
							top: 0;
							left: 0;
							z-index: 100;
							text-align: left;
							line-height: 100rpx;
							font-size: 28rpx;
							color: transparent;
						}
					}

					.get-code-btn {
						width: 150rpx;
						height: 50rpx;
						font-size: 28rpx;
						color: var(--primary-color);
						line-height: 50rpx;
						text-align: center;
						margin-left: 20rpx;
					}
				}
			}

			.popup-auth-title {
				font-size: 36rpx;
				line-height: 36rpx;
				font-weight: bold;
				color: #313131;
				text-align: center;
			}

			.popup-auth-message {
				font-size: 28rpx;
				color: #999;
				text-align: center;
				line-height: 48rpx;
				margin: 40rpx 0 0;
			}

			.popup-auth-message-1 {
				font-size: 28rpx;
				color: #999;
				text-align: center;
				line-height: 32rpx;
				margin-bottom: 40rpx;
			}

			.popup-auth-image-box {
				height: 190rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.popup-auth-image {
				height: 140rpx;
			}

			.popup-login-btn {
				width: 100%;
				height: 100%;
				text-align: center;
				line-height: 80rpx;
				color: #FFFFFF;
				font-size: 28rpx;
			}
		}

		.bind-vip-btn-box {
			width: 100%;
			height: 90rpx;

			.bind-vip-btn {
				flex: 1;
				height: 100%;
				text-align: center;
				line-height: 90rpx;
				font-size: 32rpx;

				&.cancel {
					color: #5F6267;
					margin-right: 20rpx;
				}

				&.confirm {
					color: var(--primary-color);
				}
			}
		}
	}
</style>
